import { createRouter, createWebHashHistory } from "vue-router";
import RoutesConfig from "./config";
import store from "@/store/index";
import Login from "../views/Login.vue";
import MainBox from "../views/MainBox.vue";

const routes = [
  {
    path: "/login",
    name: "login",
    component: Login,
  },
  {
    path: "/mainbox",
    name: "mainbox",
    component: MainBox,
  },
  {
    path: "/test",
    name: "test",
    component: () => import("@/views/test/UseLazyImage"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 判断路由权限
const checkPermission = (item) => {
  if (item.requireAuth) {
    return store.state.userInfo.role === 1;
  }
  return true;
};

// 添加路由，并将vuex中的isGetterRouter修改为true
const ConfigRouter = () => {
  // 根据权限配置路由
  if (!router.hasRoute("mainbox")) {
    router.addRoute({
      path: "/mainbox",
      name: "mainbox",
      component: MainBox,
    });
  }
  RoutesConfig.forEach((item) => {
    checkPermission(item) && router.addRoute("mainbox", item);
  });
  // 改变isGetterRouter状态为true，避免重复加载
  store.commit("changeGetterRouter", true);
};

// 路由拦截
router.beforeEach((to, from, next) => {
  if (to.name === "login") {
    next();
  } else {
    /* *
     * 判断浏览器中本地存储是否存在token：
     *    没有：重定向到login页面，
     *    有：判断是否是首次加载，
     *        是：加载路由配置，
     *        否：next()
     * */
    if (!localStorage.getItem("token")) {
      next({ path: "/login" });
    } else {
      // 第一次加载时，加载路由配置
      if (!store.state.isGetterRouter) {
        // 删除所有的嵌套路由
        router.removeRoute("mainbox");
        ConfigRouter();
        next({ path: to.fullPath });
      } else {
        next();
      }
    }
  }
});

export default router;
